class RootController < ApplicationController
  wechat_api
  skip_before_action :authenticate_wechat_user!, only: [:sign_in, :get_location,:order_notify]
  before_action :authenticate_location!, only: [:index]
  before_action :set_shopping_number, only: [:index, :product_search, :product_show]

  def index

    @userinfo = current_userinfo
    @wechat_session = current_wechat_session

    #热卖商品
    # online_state = State.online
    # @hot_sale_products = []
    # HotSaleGood.where({:userinfo_id => @userinfo.id}).order_by(:orderval => :asc).each do |hot|
    #   product=Product.shop_id(@userinfo.id.to_s).find(hot.product_id)
    #
    #   next if (online_state.id.to_s!=product['state_id'].to_s)
    #
    #   product["orderval"] = hot["orderval"]
    #   @hot_sale_products << product
    # end

    @hot_sale_products = RootHelper.get_hot_sale_products(@userinfo.id)

    # 轮播图
    @carousel_list = RootHelper.get_cache_carousels(@userinfo.id)

    ######加载其他的轮播图
    platform_userinfo = Userinfo.where({:role_marks => 'platform'}).cache.first
    Carousel.where(:userinfo_id => platform_userinfo.id, :field_mark => {"$in" => [5, 6]}).each do |carousel|
      @carousel_list << carousel
    end


    #商品分类
    @categorys = MobileCategory.get_cache_list_by_userinfo_id(@userinfo.id.to_s)
    @title = '酒运达微商城'
  end


  #获取openid，并且渲染定位页面
  def sign_in

    code = params[:code]

    if !code.present?
      redirect_to '/401.html'
      return
    end

    # binding.pry
    #根据code获取openId
    result = Wechat.api.web_access_token(code)
    Rails.logger.info "微信认证结果为：#{result.to_json}"
    if !result['access_token'].present?
      redirect_to '/401.html'
      return
    end

    session[:openid] = result['openid']
    #存储微信信息
    @wechat_session = WechatSession.find_or_create_by(:openid => result['openid'])
    @wechat_session.access_token = result['access_token']
    @wechat_session.refresh_token = result['refresh_token']
    @wechat_session.save

    # wechat_oauth2 do |openid|
    #   Rails.logger.info "微信认证结果为：#{openid}"
    #   @current_user = User.find_by(wechat_openid: openid)
    #   Rails.logger.info "微信认证结果为：#{openid}"
    #   @wechat_session ||= WechatSession.find_or_create_by(:openid => openid)
    # end
  end


  #获取定位信息，并且登录系统
  def get_location

    longitude = params[:longitude]
    latitude = params[:latitude]

    #根据经纬度获取 小B id
    # location_params = {:location => "#{latitude},#{longitude}", :geotable_id => '145835', :ak => '7KZQK6tPQ4w6wa7h4fk5YuOq1X5LBuyB'}

    #发送推送
    response = RestClient.get "http://api.map.baidu.com/cloudrgc/v1?location=#{latitude},#{longitude}&geotable_id=145835&ak=7KZQK6tPQ4w6wa7h4fk5YuOq1X5LBuyB"
    location_result = JSON.parse(response.body)

    province = ""
    city = ""
    district = ""
    if location_result['status'].to_i == 0
      province = location_result['address_component']['province']
      city = location_result['address_component']['city']
      district = location_result['address_component']['district']
    end

    req_params = {:province => province, :city => city, :district => district}
    Rails.logger.info "百度定位地址信息为：#{response.body}"
    Rails.logger.info "地址信息为：#{req_params.to_json}"
    city_result = ElephantServiceHelper.post_data('v1,city,current_city', req_params)
    session[:userinfo_id] = city_result['_id']

    # 刷新定位
    RootHelper.refresh_location(session.id,latitude,longitude)

    redirect_to '/'
  end


  # 商品搜索
  def product_search

    keyword = params[:keyword]
    @category_id = params[:category_id]
    search_params = {:state_id => State.online.id}
    search_params[:title] = /#{keyword}/ if keyword.present?
    search_params[:mobile_category_id] = BSON::ObjectId(@category_id) if @category_id.present?

    @title = @category_id.present? ? MobileCategory.find(@category_id).title : '商品列表'

    #商品分类
    @categorys = MobileCategory.get_cache_list_by_userinfo_id(@userinfo.id.to_s)
    @product_list = Product.shop_id(current_userinfo.id.to_s).where(search_params).to_a
    
  end


  # 商品详情
  def product_show

    userinfo = current_userinfo
    product_id = params[:product_id]
    @product = Product.shop_id(userinfo.id.to_s).find(product_id)
    @title = @product.current_title
  end


  #刷新定位
  def refresh_location
    render 'sign_in'
  end



  def order_notify

    title = params[:title]
    keyword1 = params[:keyword1]
    keyword2 = params[:keyword2]
    remark = params[:remark]
    wechat_id = params[:wechat_id]

    begin
      wechat_session = WechatSession.find(wechat_id)
    rescue
    end
    respond_to do |format|

      if wechat_session.present?
        template = YAML.load(File.read(Rails.root.join("config/template.yml")))
        template_data = template['template']
        template_data["data"]["first"]["value"] = title if title.present?
        template_data["data"]["keyword1"]["value"] = keyword1 if keyword1.present?
        template_data["data"]["keyword2"]["value"] = keyword2 if keyword2.present?
        template_data["data"]["remark"]["value"] = remark if remark.present?
        Rails.logger.info "订单通知参数为：#{template_data.to_json}"
        result = Wechat.api.template_message_send Wechat::Message.to(wechat_session.openid).template(template_data)
        Rails.logger.info "订单通知结果为：#{result.to_json}"
        format.json { render json: result }
      else
        format.json { render json: {:result => 'openid no exists'} }
      end
    end
  end


  private
  # Use callbacks to share common setup or constraints between actions.
  def set_shopping_number

    wechat_session = current_wechat_session
    userinfo = current_userinfo
    customer_id = wechat_session.customer_id.present? ? wechat_session.customer_id : wechat_session.business_id

    #获取购物车数量
    req_params = {:customer_id => customer_id,:userinfo_id=> userinfo.id.to_s}
    result_data = ElephantServiceHelper.get_data('v2,shopping_cart,number', req_params)
    @shoppingcart_number = result_data['number']

  end

end